﻿define(['app'], function(app) {
	'use strict';

	var controller = function controller($scope, Afsrue, $stateParams, $ionicPopup, GoPage, GoDialog, $ionicModal) {
		
		$scope.input = new Object();
		$scope.total_money = 0;
		var shipping_id = new Array();
		var shipping = new Object();
		$scope.input.shipping = '';
		var coupon_id = new Array();
		$scope.input.coupon_id = '';
		var invoice_id = new Array();
		var invoice = new Object();
		$scope.input.invoice = '';
		$scope.input.receiver = '';
		$scope.input.shipping_id = '';
		$scope.total_cost = 0;
		$scope.addr_id = "";
		
		$scope.$on('$ionicView.beforeEnter', function() {
			$scope.type = $stateParams.type;
			$scope.status = $stateParams.status;
			$scope.init_data();
		}, false);
		
		$scope.init_count = function() {
			for(var i = 0; i < $scope.check.order_objects.length; i++) {
				$scope.check.order_objects[i].total_count = 0;
				$scope.check.order_objects[i].total_money = 0;
				$scope.check.order_objects[i].total_count += Number($scope.check.order_objects[i].quantity);
				$scope.check.order_objects[i].total_money += Number($scope.check.order_objects[i].quantity) * Number($scope.check.order_objects[i].price);
				$scope.total_money += Number($scope.check.order_objects[i].quantity) * Number($scope.check.order_objects[i].price);
				$scope.score += Number($scope.check.order_objects[i].score) * Number($scope.check.order_objects[i].quantity);
			}
		}
		
		$scope.init = function(data) {
			if(!data) {
				GoDialog.alert("提示", "购物车已经没有商品！", function() {
					GoPage.go_tabPage('cart');
				});
			} else {
				$scope.check = data;
				if(data.vatinfo){
					$scope.input.tax_company = data.vatinfo.unit_name;
				}
				if($scope.check.delivery != null) {
					if($scope.receiverIndex == undefined ){
							if($scope.check.delivery.length > 1) {
								for(var j = 0; j < $scope.check.delivery.length; j++) {
									if($scope.check.delivery[j].def_addr == '1') {
										$scope.addr_id = $scope.check.delivery[j].addr_id;
										$scope.receiver = $scope.check.delivery[j];
										$scope.receiverIndex = j; //默认是第一个
										break;
									}
								}
							} else {
								$scope.addr_id = $scope.check.delivery[0].addr_id;
								$scope.receiver = $scope.check.delivery[0];
							}
						}
				} else {
					$scope.addr_id = '';
					$scope.receiver = '';
				}

				for(var i = 0; i < $scope.check.order_items.length; i++) {
					if($scope.check.order_items[i].shipping){
						$scope.check.order_items[i].shipping_id = $scope.check.order_items[i].shipping[0].id;
						$scope.check.order_items[i].shipping_name = $scope.check.order_items[i].shipping[0].name;
						$scope.check.order_items[i].shipping_money = $scope.check.order_items[i].shipping[0].money;
					}
					if(!$scope.check.order_items[i].cpns_name) {
						$scope.check.order_items[i].cpns_prefix = '';
						$scope.check.order_items[i].cpns_name = '不使用优惠券';
					}
					for(var n = 0; n < $scope.check.order_items[i].slips.length; n++) {
						for(var m = 0; m < $scope.check.order_items[i].slips[n].items.length; m++) {
							$scope.check.order_items[i].total_count = 0;
							if($scope.check.order_items[i].slips[n].items[m].invoice_type != null && $scope.check.order_items[i].slips[n].items[m].invoice_type.length > 0) {
								$scope.check.order_items[i].slips[n].items[m].invoice_value = $scope.check.order_items[i].slips[n].items[m].invoice_type[0].type;
							}
							$scope.check.order_items[i].total_count += $scope.check.order_items[i].slips[n].items[m].num;
							$scope.total_cost = $scope.check.order_items[i].slips[n].items[m].num * $scope.check.order_items[i].slips[n].items[m].price;
						}
					}
				}
				$scope.init_shipping();
			}
		}
		
		//数据初始化
		$scope.init_data = function() {
			$scope.isApplyInvoice = false;//是否索要发票，不开发票时，发票抬头+税号都不显示。接口默认不开发票
			if($scope.type != '' && $scope.type != 'goods') {
				Afsrue.get_data($scope.type, function(data) {
					console.log(data)
					$scope.init(data);
				})
			} else {
				Afsrue.get_checkout($scope.addr_id, $scope.status, $scope.type, function(data) {
					$scope.init(data);
				});
			}
		}

		$scope.init_shipping = function() {
			shipping_id = new Array();
			for(var i = 0; i < $scope.check.order_items.length; i++) {
				if($scope.check.order_items[i].shipping){
					shipping_id[i] = $scope.check.order_items[i].shipping[0].id;
				}
			}
			$scope.input.shipping_id = JSON.stringify(shipping_id);
		}
		
		$scope.update_total = function() {
			if(coupon_id.length == 0){
				$scope.input.coupon_id = '';
			}else{
				$scope.input.coupon_id = JSON.stringify(coupon_id);
			}
			if(shipping_id.length == 0){
				$scope.input.shipping_id = '';
			}else{
				$scope.input.shipping_id = JSON.stringify(shipping_id);
			}
			if(invoice_id.length == 0){
				$scope.input.invoice_id = '';
			}else{
				$scope.input.invoice_id = JSON.stringify(invoice_id);
			}
			if($scope.type == '' || $scope.type == 'goods'||$scope.type=='fastbuy') {
				Afsrue.update_total($scope.addr_id, $scope.input.shipping_id, $scope.input.coupon_id, $scope.input.invoice_id, $scope.status, $scope.type, function(data) {
					$scope.check.order_detail.total_amount = data.total_amount;
					$scope.check.order_detail.totalGainScore = data.totalGainScore;
					for(var i = 0; i < $scope.check.order_items.length; i++) {
						$scope.check.order_items[i].store_slip_subtotal = data.store_amount[i];
					}
					if(data.msg) {
						coupon_id[$scope.store_index].value = '';
						$scope.check.order_items[$scope.store_index].cpns_name = '不使用优惠券';
						$scope.check.order_items[$scope.store_index].cpns_prefix = '';
						GoDialog.toast(data.msg);
					} else {
						if(data.store_amount != undefined)
							$scope.check.md5_cart_info = data.md5_cart_info;
						for(var key in data.goods_price) {
							for(var i = 0; i < $scope.check.order_items.length; i++) {
								if($scope.check.order_items[i].store_id == key) {
									for(var index in data.goods_price[key]) {
										for(var n = 0; n < $scope.check.order_items[i].slips.length; n++) {
											for(var j = 0; j < $scope.check.order_items[i].slips[n].items.length; j++) {
												if(index == $scope.check.order_items[i].slips[n].items[j].product_id) {
													$scope.check.order_items[i].slips[n].items[j].price = data.goods_price[key][index];
												}
											}
										}
									}
								}
							}
						}
					}
				})
			} else {//活动商品
				Afsrue.update_atotal($scope.addr_id, "no", JSON.parse($scope.input.shipping_id), JSON.parse($scope.input.shipping_id)[0], $scope.check.order_items[0].store_id, $scope.check.slips_id, $scope.check.split_order, $scope.type, function(data) {
					if(data.success == true) {
						$scope.check.order_items[0].store_slip_subtotal = data.result.store_subtotal;//小计。一次只能买一种，所以这里直接写为0，无需循环
						$scope.check.order_detail.total_amount = data.result.store_subtotal;//总
					} else {
						GoDialog.toast(data.msg);
						$scope.init_data();
					}
				})
			}
		}
		
		//提交
		$scope.submit = function() {
			invoice = new Object();
			shipping = new Object();
			$scope.input.receiver = JSON.stringify($scope.receiver);
			if($scope.input.receiver == null || $scope.receiver == "") {
				GoDialog.alert("提示", "请先设置收货地址",function(){
					GoPage.go_states("t-address");
				});
				return;
			}
			var is_show_tax = false;//是否要开发票
			var is_person_tax = false;//是否是"个人发票",如果是,则发票抬头比填
			for(var i = 0; i < $scope.check.order_items.length; i++) {
				shipping[$scope.check.order_items[i].store_id] = new Object();
				shipping[$scope.check.order_items[i].store_id][800] = new Object();
				shipping[$scope.check.order_items[i].store_id][800].shipping_id = $scope.check.order_items[i].shipping_id;
				shipping[$scope.check.order_items[i].store_id][800].memo = $scope.check.order_items[i].memo;
				invoice[$scope.check.order_items[i].store_id] = new Object();
				invoice[$scope.check.order_items[i].store_id][800] = new Object();
				var invoice_value = new Array();
				for(var n = 0; n < $scope.check.order_items[i].slips.length; n++) {
					for(var j = 0; j < $scope.check.order_items[i].slips[n].items.length; j++) {
						if($scope.check.order_items[i].slips[n].items[j].invoice_type != null && $scope.check.order_items[i].slips[n].items[j].invoice_type.length > 0) {
							invoice_value[invoice_value.length] = {
								'type': $scope.check.order_items[i].slips[n].items[j].invoice_value,
								'goods_id': $scope.check.order_items[i].slips[n].items[j].goods_id,
								'product_id': $scope.check.order_items[i].slips[n].items[j].product_id,
								'trigger_tax': $scope.check.order_items[i].slips[n].items[j].hastax
							}
							if($scope.check.order_items[i].slips[n].items[j].invoice_value != 'no') {
								is_show_tax = true;
							}
							if($scope.check.order_items[i].slips[n].items[j].invoice_value=="person"){//用户选择“个人发票”，发票抬头则为必填项
								is_person_tax = true;
							}
						}
					}
				}
				if(invoice_value.length > 0) {
					invoice[$scope.check.order_items[i].store_id][800] = invoice_value;
				}
			}
			$scope.input.shipping = JSON.stringify(shipping);
			$scope.input.invoice = JSON.stringify(invoice);
			if($scope.type != '' && $scope.type != 'goods'&&$scope.type!='fastbuy') {
				var param = new Object();
				param.receiver = $scope.input.receiver;
				param.shipping = $scope.input.shipping;
				param.invoice = $scope.input.invoice;
				param.md5_cart_info = $scope.check.md5_cart_info;
				param.purchase = JSON.stringify($scope.check.purchase);
				param.extends_args = $scope.check.extends_args;
				param.split_order = $scope.check.split_order;
				param.business_goods = $scope.check.business_goods;
				Afsrue.go_pay(param, $scope.check.act_id, $scope.type, function(data) {
					if(data.success == true) {
						var order = new Array();
						order[0] = data.result;
						order = JSON.stringify(order);
						GoDialog.toast("订单创建");
						GoPage.go_states_back("afpay", {
							"order_id": order
						});
					} else {
						if(data.msg == '操作失败，购物车为空！') {
							GoPage.go_states_back("afall", {
								'type': 1
							});
						} else if(data.msg == '操作失败，请重新提交！') {
							GoPage.go_states_back("afall", {
								'type': 1
							});
						} else
							GoDialog.toast(data.msg);
					}
				})
			} else {
				var tax_company = "";
				if(is_show_tax) {
					tax_company = $scope.input.tax_company;
				}
				if(is_person_tax&&!tax_company){
					GoDialog.toast("个人发票的发票抬头不能为空");
					return;
				}
				Afsrue.create_pay($scope.input.receiver, $scope.input.shipping, $scope.input.invoice, $scope.check.md5_cart_info, $scope.status, $scope.type, tax_company, function(data) {
					if(data.success == true) {
						var order = new Array();
						order = data.result.orders;
						order = JSON.stringify(order);
						GoDialog.toast("订单创建");
						GoPage.go_states_back("afpay", {
							"order_id": order
						});
					} else {
						if(data.msg == '操作失败，购物车为空！') {
							GoPage.go_states_back("afall", {
								'type': 1
							});
						} else if(data.msg == '操作失败，请重新提交！') {
							GoPage.go_states_back("afall", {
								'type': 1
							});
						} else{
							GoDialog.toast(data.msg);
						}
					}
				})
			}
		}
		
		/***************选择优惠券**************/
		$ionicModal.fromTemplateUrl("templates/modal/afsrue_coupon.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_coupon = modal;
		});
		//打开
		$scope.openModal_coupon = function(index) {
			$scope.couponList = $scope.check.order_items[index].coupon;//地址传递
			$scope.store_index = index;//店铺下标
			$scope.modal_coupon.show();
		}
		//隐藏
		$scope.closeModal_coupon = function() {
			$scope.modal_coupon.hide();
		}
		//选择优惠券
		$scope.selectCoupon = function(index){
			$scope.couponList_index = index;//index=-1表示"不使用优惠券"
		}
		//确定优惠券
		$scope.getCoupon = function() {
			$scope.closeModal_coupon();
			if($scope.couponList_index==undefined) return;
			var cpns_prefix = ""
			var cpns_name = "不使用优惠券";
			var cpns_money = 0;
			if($scope.couponList_index != -1) {//-1表示"不适用优惠券"
				var cpnsData = $scope.couponList[$scope.couponList_index];
				cpns_name = cpnsData.cpns_name;
				cpns_money = cpnsData.cpns_money
				cpns_prefix = cpnsData.cpns_prefix;
			}
			var data =  $scope.check.order_items[$scope.store_index];
			data.cpns_prefix = cpns_prefix;
			data.cpns_name = cpns_name;
			data.cpns_money = cpns_money;
			$scope.get_coupon_id();
		}
		$scope.get_coupon_id = function() {
			coupon_id = new Array();
			for(var i = 0; i < $scope.check.order_items.length; i++) {
				if($scope.check.order_items[i].cpns_name != undefined) {
					if($scope.check.order_items[i].cpns_name == '不使用优惠券')
						coupon_id[i] = {
							'store_id': $scope.check.order_items[i].store_id,
							'value': ''
						};
					else {
						coupon_id[i] = {
							'store_id': $scope.check.order_items[i].store_id,
							'value': $scope.check.order_items[i].cpns_prefix
						};
					}
				} else {
					coupon_id[i] = {
						'store_id': $scope.check.order_items[i].store_id,
						'value': ''
					};
				}
			}
			$scope.update_total();
		}
		/***************选择优惠券**************/
		
		/***************配送方式**************/
		$ionicModal.fromTemplateUrl("templates/modal/afsrue_express.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_express = modal;
		});
		//打开
		$scope.openModal_express = function(index) {
			$scope.order_items = $scope.check.order_items[index];
			$scope.expressList = $scope.order_items.shipping;//地址传递
			$scope.modal_express.show();
		}
		//隐藏
		$scope.closeModal_express = function() {
			$scope.modal_express.hide();
		}
		//选择快递
		$scope.selectExpress = function(index){
			$scope.expressList_index = index;
		}
		$scope.getExpress = function() {
			$scope.closeModal_express();
			if($scope.expressList_index==undefined) return;
			var expressData = $scope.expressList[$scope.expressList_index];
			$scope.order_items.shipping_id = expressData.id;
			$scope.order_items.shipping_name = expressData.name;
			$scope.order_items.shipping_money = expressData.money;
			$scope.get_shipping_id();
		}
		$scope.get_shipping_id = function(store_id) {
			shipping_id = new Array();
			for(var i = 0; i < $scope.check.order_items.length; i++) {
				shipping_id[i] = $scope.check.order_items[i].shipping_id;
			}
			$scope.update_total();
		}
		/***************配送方式**************/
		
		/***************选择发票**************/
		$ionicModal.fromTemplateUrl("templates/modal/afsrue_invoice.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_invoice = modal;
		});
		//打开
		$scope.openModal_invoice = function(data) {
			if(!data.invoice_type){
				GoDialog.alert("提示","对不起，没有可供选择的发票形式！");
				return;
			}
			$scope.goods_items = data;//地址传递
			$scope.modal_invoice.show();
		}
		//隐藏
		$scope.closeModal_invoice = function() {
			$scope.modal_invoice.hide();
		}
		//选择发票
		$scope.selectInvoice = function(index){
			$scope.invoiceList_index = index;
		}
		//确定发票
		$scope.getInvoice = function(data){
			$scope.closeModal_invoice();
			if($scope.invoiceList_index==undefined) return;
			var invoice_value = data.invoice_type[$scope.invoiceList_index].type;
			var invoice_name = data.invoice_type[$scope.invoiceList_index].name;//显示用
			data.invoice_value = invoice_value;
			data.invoice_name = invoice_name;
			$scope.onshowtax(data.hastax,invoice_value);
		}
		$scope.onshowtax = function(hastax, invoice_value) {
			var invoiceArr = new Array();//判断是否开个人发票用，不提交
			$scope.isApplyInvoice = false;
			for(var i = 0; i < $scope.check.order_items.length; i++) {
				var invoice = new Array();
				for(var n = 0; n < $scope.check.order_items[i].slips.length; n++) {
					for(var j = 0; j < $scope.check.order_items[i].slips[n].items.length; j++) {
						var items = $scope.check.order_items[i].slips[n].items[j];
						if(items.invoice_type != null && items.invoice_type.length > 0) {//有发票数组
							invoice[invoice.length] = {
								'type': items.invoice_value,
								'goods_id': items.goods_id,
								'product_id': items.product_id,
								'trigger_tax': items.hastax
							};
							if(items.invoice_value!="no"){//只要有一个开发票，就显示发票抬头
								$scope.isApplyInvoice = true;
							}
							invoiceArr.push(items.invoice_value)
						}
					}
				}
				if(invoice.length > 0) {
					invoice_id[$scope.check.order_items[i].store_id] = new Array();
					invoice_id[$scope.check.order_items[i].store_id][800] = invoice;
				}
			}
			$scope.isPersonInvoice = true;
			for (var i=0;i<invoiceArr.length;i++) {//个人发票，不显示税号
				if(invoiceArr[i]=="normal"||invoiceArr[i]=="vat"){
					$scope.isPersonInvoice = false;
					break;
				}
			}
			$scope.update_total();
		}
		/***************选择发票**************/
		
		/*********选择收货人和收货地址**********/
		$ionicModal.fromTemplateUrl("templates/modal/afsrue_delivery.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_delivery = modal;
		});
		//打开
		$scope.openModal_delivery = function() {
			if($scope.check.delivery.length>1){//2个及2个以上才显示弹窗
				$scope.modal_delivery.show();
			}
		}
		//隐藏
		$scope.closeModal_delivery = function() {
			$scope.modal_delivery.hide();
		}
		//选择收货人
		$scope.selectDelivery = function(index){
			$scope.deliveryList_index = index;
		}
		//确定收货人
		$scope.getDelivery = function(go_address) {
			if(go_address == 0) {
				GoPage.go_states("t-address");
			} else {
				$scope.closeModal_delivery();
				if($scope.deliveryList_index==undefined) return;
				$scope.receiver = $scope.check.delivery[$scope.deliveryList_index];
				$scope.addr_id = $scope.check.delivery[$scope.deliveryList_index].addr_id;
				if($scope.receiverIndex != $scope.deliveryList_index) {
					if($scope.type ==''||$scope.type=='goods'||$scope.type=='fastbuy'){
						$scope.init_data();
					}
				}
				$scope.receiverIndex = $scope.deliveryList_index;
			}
		}
		/*********选择收货人和收货地址**********/

		//页面跳转
		/*$scope.onshow_first = function(store_id) {
			GoPage.go_states("first", {
				"store_id": store_id
			});
		}
		//跳转到商品详情。 on-tap="onshow_product(adjunct.goods_id,adjunct.type)"
		$scope.onshow_product = function(goods_id, type) {
			var url = '';
			if(type != "normal" && type != "goods" && type != '') {
				if(type == "groupbuy") {
					url = "groupbuy_goods";
				} else if(type == "seckill") {
					url = "seckill_goods";
				} else if(type == "timedbuy") {
					url = "panicbuying_goods";
				}
				GoPage.go_states(url, {
					"act_id": $scope.check.act_id,
					"goods_id": goods_id
				});
			} else {
				if(type == "normal") {
					type = 'goods';
				}
				GoPage.go_states("productdetail", {
					'goods_id': goods_id,
					'type': type
				});
			}
		}*/
		
		//优惠信息,超过3个
		$scope.showMoreProInfo = function(){
			$scope.isMoreProInfo = !$scope.isMoreProInfo;
		}
		
		//清空输入
		$scope.clearInput = function(type){
			if(type==1){
				$scope.order_items.memo = "";
			}else{
				$scope.input.tax_company = "";
			}
		}
		
		//点击“感叹号”显示信息
		$scope.showTipInfo = function($event){
			$event.stopPropagation();//阻止事件冒泡
			GoDialog.alert("提示","如果要开具增值税发票，请先到个人中心填写增票资质");
		}
		

	}

	controller.$inject = ['$scope', 'Afsrue', '$stateParams', '$ionicPopup', 'GoPage', 'GoDialog','$ionicModal'];

	return app.registerController("afsruectrl", controller);
});